package com.juyu.miliao.api.dao.elasticsearch;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.api.dao.redis.usercache.UserCacheVo;
import com.juyu.miliao.api.dao.redis.usercache.UserInfoCache;
import com.juyu.miliao.api.domain.FindDynamicGiftInfo;
import com.juyu.miliao.api.domain.vo.FindDynamicGiftVO;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.tophits.TopHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author xuanqicheng
 */
@Repository
public class FindDynamicGiftInfoElasticsearch {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserInfoCache userInfoCache;



    public void addFindDynamicGiftSendInfo(FindDynamicGiftInfo findDynamicGiftInfo) throws IOException {
        IndexRequest request = new IndexRequest("find_dynamic_gift_info", "findDynamicGiftInfo",
                findDynamicGiftInfo.getId() + "");

        request.source(objectMapper.writeValueAsString(findDynamicGiftInfo), XContentType.JSON);

        restHighLevelClient.index(request, RequestOptions.DEFAULT);
    }

    public FindDynamicGiftVO getFindDynamicGiftVO(int findId) throws IOException {
        SearchRequest searchRequest = new SearchRequest("find_dynamic_gift_info");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        searchSourceBuilder.size(0);
        boolQueryBuilder.must(QueryBuilders.termQuery("findId",findId));
        searchSourceBuilder.query(boolQueryBuilder);
        AggregationBuilder agg = AggregationBuilders.terms("agg").field("sendUserId").size(5);
        searchSourceBuilder.aggregation(agg);
        searchSourceBuilder.timeout(new TimeValue(10, TimeUnit.SECONDS));

        searchRequest.source(searchSourceBuilder);

        SearchResponse res = restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
        List<String>  iconList = new ArrayList<>();
        long total = res.getHits().getTotalHits();
        if(total>0){
            Terms terms = res.getAggregations().get("agg");
            for (Terms.Bucket entry : terms.getBuckets()) {
                long userId= entry.getKeyAsNumber().longValue();
                UserCacheVo userCacheVo =userInfoCache.getUserCacheInfo(userId);
                iconList.add(userCacheVo.getIcon());
            }
        }
        FindDynamicGiftVO findDynamicGiftVO = new FindDynamicGiftVO();
        findDynamicGiftVO.setTotal(total);
        findDynamicGiftVO.setSendUserList(iconList);
        return findDynamicGiftVO;
    }
}
